<script setup lang="ts">
import { onMounted, reactive } from 'vue'
// import { answerList, puzzleList } from '@/assets/proverb.json'
import MultipleChoice from '@/components/multiple-choice.vue'
import { seededRandomer, shuffleArray, swapElements } from '@/utils'
import DataBase from '@tauri-apps/plugin-sql'

const answerList: string[] = reactive([])
const puzzleList: string[] = reactive([])

let currentIdx = 0
let db: null | DataBase = null

onMounted(async () => {
  db = await DataBase.load('sqlite:base.db')
  currentIdx = (
    (await db.select(
      "SELECT value FROM history WHERE item='proverb'"
    )) as Array<{
      item: string
      value: number
    }>
  )[0].value

  console.log('currentIndex', currentIdx)

  const r = (await db.select(`SELECT idiom,explain from proverb`)) as Array<{
    idiom: string
    explain: string
  }>

  for (const i of r) {
    answerList.push(i.idiom)
    puzzleList.push(i.explain)
  }

  shuffleList()
})

const onAdvance = async () => {
  currentIdx++
  await db?.execute(
    `UPDATE history SET value=${currentIdx} WHERE item='proverb'`
  )
}

const onSuccess = async () => {
  await db?.execute(
    `UPDATE history SET value=${Date.now()} WHERE item='proverb-random'`
  )
  await db?.execute(`UPDATE history SET value=0 WHERE item='proverb'`)
}

const shuffleList = async () => {
  const seed = (await db?.select(
    "SELECT value FROM history WHERE item='proverb-random'"
  )) as Array<{
    item: string
    value: number
  }>

  console.log('random-seed', seed[0].value)
  const randomGenerator = seededRandomer(seed[0].value)

  const shuffled = shuffleArray(
    Array.from({ length: answerList.length / 2 }).map(
      (_, i) => i + Math.round(answerList.length / 2)
    ),
    randomGenerator
  )
  for (let i = 0; i < shuffled.length; i++) {
    swapElements(answerList, i, shuffled[i])
    swapElements(puzzleList, i, shuffled[i])
  }
  // console.log(shuffled)
}
</script>

<template>
  <MultipleChoice
    :answer-list="answerList.slice(currentIdx)"
    :puzzle-list="puzzleList.slice(currentIdx)"
    @advance="onAdvance"
    @success="onSuccess"
  ></MultipleChoice>
</template>
